package com.voxel.sense.infomsg.module.task.execution;

import android.os.Environment;
import android.support.annotation.NonNull;

import com.example.com.common.app.BasePresenter;
import com.example.com.common.factory.data.DataSource;
import com.example.com.common.utils.L;
import com.example.com.common.utils.ToastUtil;
import com.google.gson.Gson;
import com.lzy.okgo.model.Progress;
import com.lzy.okserver.OkUpload;
import com.lzy.okserver.upload.UploadTask;
import com.voxel.sense.infomsg.App;
import com.voxel.sense.infomsg.data.FileImageInfo;
import com.voxel.sense.infomsg.interfaces.listener.UploadListenerImp;
import com.voxel.sense.infomsg.net.helper.TaskManagerNetHelper;
import com.voxel.sense.infomsg.utils.UploadUtils;

import java.io.File;
import java.util.ArrayList;

import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.net.RequestIdFactory;

/**
 * Created by ChenYiYao on 2018/3/27.
 */

public class TaskExecutionPresenter extends BasePresenter<TaskExecutionContract.View>
        implements TaskExecutionContract.Presenter, DataSource.Callback<BaseEntity> {

    private ArrayList<String> mSelectImagePath;//选择图片返回的path
    private ArrayList<String> mSelectDocuPath;//选择文档返回的path
    private ArrayList<String> mSelectVideoPath;//选择视频返回的path
    private String mTaskNumber;

    @Override
    public void start() {
        super.start();
        mSelectImagePath = new ArrayList<>();
        mSelectDocuPath = new ArrayList<>();
        mSelectVideoPath = new ArrayList<>();
        initCameraConfig();
    }

    @Override
    public void destroy() {
        super.destroy();
        if (mUploadListener.getTask() != null) {
            mUploadListener.getTask().remove();
        }
        mUploadListener = null;
    }

    public TaskExecutionPresenter(TaskExecutionContract.View view) {
        super(view);
    }

    @Override
    public void doTakePhotoFinish(File file) {
        //由于最末尾是添加的图标，当有图片的时候和选中数小于size-1的时候插入的位置才是size-1，不然位置会错乱
        //Constants.UPLOAD_FILE_MAX_COUNT-1 是因为数组包含了添加的item
        if (mSelectImagePath.size() > 0 && mSelectImagePath.size() < Constants.UPLOAD_FILE_MAX_COUNT-1) {
            mSelectImagePath.add(mSelectImagePath.size() - 1, file.getPath());
        } else {
            mSelectImagePath.add(file.getPath());
        }
        ArrayList<FileImageInfo> fileImageInfos = makeGalleryDatas(mSelectImagePath);
        mView.onRefreshPhoto(fileImageInfos);

    }

    @Override
    public void doLoadGalleryData(ArrayList<String> datas) {
        if (datas == null)
            return;

        mSelectImagePath.clear();
        mSelectImagePath.addAll(datas);
        //构造图片墙的数据
        ArrayList<FileImageInfo> list = makeGalleryDatas(datas);
        mView.onRefreshPhoto(list);
    }

    @NonNull
    private ArrayList<FileImageInfo> makeGalleryDatas(ArrayList<String> datas) {
        ArrayList<FileImageInfo> list = new ArrayList<>();
        for (String path : datas) {
            File file = new File(path);
            if (file.exists()) {
                FileImageInfo fileImageInfo = new FileImageInfo(file.getName(), file.getPath());
                list.add(fileImageInfo);
            }
        }
        return list;
    }

    @Override
    public void doDisposeDocData(ArrayList<String> datas) {
        if (datas == null)
            return;
        mSelectDocuPath.clear();
        mSelectDocuPath.addAll(datas);
        ArrayList<FileImageInfo> list = makeGalleryDatas(datas);
        mView.onRefreshDoc(list);
    }

    @Override
    public void doDisposeVideoDatas(ArrayList<String> datas) {
        if (datas == null)
            return;
        mSelectVideoPath.clear();
        mSelectVideoPath.addAll(datas);
        ArrayList<FileImageInfo> beans = makeGalleryDatas(datas);
        mView.onRefreshVideo(beans);
    }


    @Override
    public void doSubmitTask(String taskNumber) {
        mTaskNumber = taskNumber;
        TaskManagerNetHelper.executeTask(taskNumber, this);
    }

    @Override
    public void doCancleUpLoad() {
        //停止上传
        OkUpload instance = OkUpload.getInstance();
        boolean b = instance.hasTask(mTaskNumber);
        //TODO: 这里的移除存在问题，并不能真正取消网络
        L.d(mTaskNumber + "instance.hasTask(mTag):" + b);
        mUploadListener.getTask().pause();
        UploadTask remove = mUploadListener.getTask().remove();
        L.d("停止下载。。。。。");
    }

    @Override
    public void removePhotoDatas(int position) {
        mSelectImagePath.remove(position);
    }

    @Override
    public void removeVideoDatas(int position) {
        mSelectVideoPath.remove(position);
    }

    @Override
    public void removeDocDatas(int position) {
        mSelectDocuPath.remove(position);
    }


    /**
     * 初始化视频录制配置.
     */
    private void initCameraConfig() {
        //初始化视频拍摄的配置
        // 设置拍摄视频缓存路径
        File dcim = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
//        if (DeviceUtils.isZte()) {
//            if (dcim.exists()) {
//                JianXiCamera.setVideoCachePath(dcim + "/mabeijianxi/");
//            } else {
//                JianXiCamera.setVideoCachePath(dcim.getPath().replace("/sdcard/",
//                        "/sdcard-ext/")
//                        + "/mabeijianxi/");
//            }
//        } else {
//            JianXiCamera.setVideoCachePath(dcim + "/mabeijianxi/");
//        }
//        // 初始化拍摄，遇到问题可选择开启此标记，以方便生成日志
//        JianXiCamera.initialize(false, null);
    }

    @Override
    public void onDataLoaded(BaseEntity data, int reqId) {
        if (mView == null)
            return;

        if (reqId == RequestIdFactory.EXECUTE_TASK) {
            if (data != null && data.isSuccess()) {
                if (mSelectImagePath != null && mSelectImagePath.size() > 0) {
                    UploadUtils.getInstent().getTaskPostUpRequest(Constants.up_load_type_photo + "", mTaskNumber, mSelectImagePath, mUploadListener);
                } else if (mSelectDocuPath != null && mSelectDocuPath.size() > 0) {
                    UploadUtils.getInstent().getTaskPostUpRequest(Constants.up_load_type_douc + "", mTaskNumber, mSelectDocuPath, mUploadListener);
                } else if (mSelectVideoPath != null && mSelectVideoPath.size() > 0) {
                    UploadUtils.getInstent().getTaskPostUpRequest(Constants.up_load_type_vide + "", mTaskNumber, mSelectVideoPath, mUploadListener);
                } else {
                    mView.onUpLoadComeplete();

                }

            } else {
                mView.onUpLocadFailure();
            }
        }
    }

    @Override
    public void onDataNotAvailable(String strRes, int reqId) {
        ToastUtil.showToastLong(App.getInstance().getApplicationContext(),strRes);
    }


    private UploadListenerImp<String> mUploadListener = new UploadListenerImp<String>() {
        boolean isUploadComplete = false;

        @Override
        public void init() {
            super.init();

        }

        @Override
        public void onFinish(String entity, Progress progress) {
            super.onFinish(entity, progress);
            Gson gson = new Gson();
            BaseEntity baseEntity = gson.fromJson(entity, BaseEntity.class);
            String tag = (String) progress.extra1;
            getTask().remove();
            getTask().unRegister(progress.tag);
            if (baseEntity != null && baseEntity.isSuccess()) {
                switch (tag) {
                    case Constants.up_load_type_photo://图片上传结束
                        //图片上传结束，查看是否有文档需要上传
                        if (mSelectDocuPath != null && mSelectDocuPath.size() > 0) {
                            UploadUtils.getInstent().getTaskPostUpRequest(1 + "", mTaskNumber, mSelectDocuPath, this);
                        } else if (mSelectVideoPath != null && mSelectVideoPath.size() > 0) {
                            UploadUtils.getInstent().getTaskPostUpRequest(2 + "", mTaskNumber, mSelectVideoPath, this);
                        } else {
                            //加载完成
                            upLoadEnd(true);
                        }
                        break;
                    case Constants.up_load_type_douc://文档上传结束
                        //                msg = "正在上传文档";
                        if (mSelectVideoPath != null && mSelectVideoPath.size() > 0) {
                            UploadUtils.getInstent().getTaskPostUpRequest(2 + "", mTaskNumber, mSelectVideoPath, this);
                        } else {
                            //加载完成
                            upLoadEnd(true);
                        }
                        break;
                    case Constants.up_load_type_vide://视频上传结束
                        upLoadEnd(true);
                        break;
                }
            } else {
                ToastUtil.showToastLong(Factory.app(), "任务执行单提交失败");
                upLoadEnd(false);
            }

        }

        /**
         *
         * @param b true为上传成功 ，false失败
         */
        private void upLoadEnd(boolean b) {
            isUploadComplete = true;
            if (b) {
                mView.onUpLoadComeplete();
            } else {
                mView.onUpLocadFailure();
            }
        }

        @Override
        public void onProgress(Progress progress) {
            super.onProgress(progress);
            if (mView != null) {
                mView.setUpLoadProgress((int) (progress.fraction * 1000));
            }
            int pro = (int) (progress.fraction * 100);
            L.d("onProgress--:" + pro);
        }

        @Override
        public void onError(Progress progress) {
            super.onError(progress);
            if (mView == null) {
                return;
            }
            isUploadComplete = true;
            mView.onUpLocadFailure();
            L.d("onError--:" + progress.totalSize);
        }

        @Override
        public void onRemove(Progress progress) {
            super.onRemove(progress);
            if (mView == null) {
                return;
            }
            isUploadComplete = true;
            L.d("--onRemove--:" + progress.tag + "---extra1:" + progress.extra1);
        }

        @Override
        public void onStart(Progress progress) {
            super.onStart(progress);
            if (mView == null)
                return;

            String tag = (String) progress.extra1;
            String msg = "";

            switch (tag) {
                case Constants.up_load_type_photo://图片上传结束
                    msg = "正在上传图片";
                    break;
                case Constants.up_load_type_douc://文档上传结束
                    msg = "正在上传文档";
                    break;
                case Constants.up_load_type_vide://视频上传结束
                    msg = "正在上传视频";
                    break;
            }
            mView.showUpLoadProgress(0, msg);
            //进度窗口消失监听
            isUploadComplete = false;
        }
    };

}
